package com.ipharma.application.services;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import com.ipharma.McdError;
import com.ipharma.McdPrs;
import com.ipharma.beans.Helper;
import com.ipharma.config.Config;
import com.ipharma.config.Session;
import com.ipharma.dto.Product;
import com.ipharma.model.ContenidoDispenser;
import com.ipharma.model.Producto;
import com.ipharma.model.RetornosDispenser;
import com.ipharma.service.DispenserService;
import com.ipharma.service.ProductoService;

/**
 * A RecycleBin class.
 * <P>
 * 
 * @author JorgE.H
 */
public class RecycleBin extends Object {

   /**
    * Attributes
    */
   List vProducts;

   ProductoService productoService;

   Session theSess;

   int dispId;

   /**
    * Constructor
    */
   public RecycleBin(Session pSess) {

      try {
         theSess = pSess;
         Config config = (Config) theSess.get(McdPrs.CONFIG);
         dispId = Integer.parseInt(config.getDispenser());
         productoService = Helper.getProductoService();
      } catch (Exception e) {
         McdError.add(e);
      }
   }

   /**
    * Adds a product to the recycle bin
    * 
    * @param pProd
    *           a product object
    */
   public void addProduct(Product pProd) throws Exception {

      boolean lb_found = false;
      Product l_prod;

      // checks if product is already in vector
      for (int i = 0; i < vProducts.size(); i++) {
         // updates vector
         l_prod = (Product) vProducts.get(i);
         if (l_prod.equals(pProd)) {
            l_prod.setQuantity(pProd.getQuantity());
            // inserts record in DB or updates it if already in DISPENSER_RETURN
            // inserts the new product into database
            RetornosDispenser retornosDispenser = new RetornosDispenser();
            retornosDispenser.setCantidad(new Integer(pProd.getQuantity()));
            retornosDispenser.setDescripcion(McdPrs.stsExtErr);
            Producto producto = productoService.findProductoById(new Long(
                  pProd.getId()));
            retornosDispenser.setProducto(producto);

            productoService.insert(retornosDispenser, new Long(dispId));

            break;
         }
      }
   }

   /**
    * Returns the content of the bin
    * 
    * @return a Vector of Products
    */
   public List getProducts() throws Exception {

      Product l_prod;
      String ls_pdtDescription, ls_pdtCode;
      int li_pdtQuantity = 0, li_pdtId;
      vProducts = new Vector();

      // reads products of recycle bin from DB
      DispenserService dispenserService = Helper.getDispenserService();
      List l_rs = dispenserService.getRetornosDelDispenser(new Long(dispId));
      for (Iterator iter = l_rs.iterator(); iter.hasNext();) {
         RetornosDispenser retorno = (RetornosDispenser) iter.next();
         ls_pdtDescription = retorno.getProducto().getDescripcion();
         ls_pdtCode = retorno.getProducto().getCodigo();
         li_pdtId = retorno.getProducto().getId().intValue();
         li_pdtQuantity = retorno.getCantidad().intValue();

         l_prod = new Product(ls_pdtDescription, li_pdtQuantity, ls_pdtCode, true);
         l_prod.setId(li_pdtId);

         // fills a vector with Product objects
         vProducts.add(l_prod);
    
      }
      
      // reads from DB dispenser products that aren't in recycle bin yet
      l_rs = dispenserService.selectOuterContent(new Long(dispId));
      
     for (Iterator iter = l_rs.iterator(); iter.hasNext();) {
        ContenidoDispenser contenidoDispenser = (ContenidoDispenser) iter.next();
        ls_pdtDescription = contenidoDispenser.getProductoDispenser().getProducto().getDescripcion();
        ls_pdtCode = contenidoDispenser.getProductoDispenser().getProducto().getCodigo();
        li_pdtId = contenidoDispenser.getProductoDispenser().getProducto().getId().intValue();
        li_pdtQuantity = 0;

        l_prod = new Product(ls_pdtDescription, li_pdtQuantity, ls_pdtCode, true);
        l_prod.setId(li_pdtId);

         // fills a vector with Product objects
         vProducts.add(l_prod);
      }
      
      
      // returns a vector with current products in bin
      return vProducts;
   }

   /**
    * Returns the product object corresponding to pCode
    * 
    * @return a Product object or null if pCode does'nt exist in RecycleBin
    */
   public Product getProduct(String pCode) throws Exception {

      ProductoService dbProd = Helper.getProductoService();
      Product l_prod = null;

      for (int i = 0; i < vProducts.size(); i++) {
         l_prod = (Product) vProducts.get(i);
         if (l_prod.getCode().equals(pCode))
            return l_prod;
      }
      // if product not in vector, searches it in DB
      List l_rs = dbProd.findByCode(pCode); // solo retorna una instancia
      for (Iterator iter = l_rs.iterator(); iter.hasNext();) {
         Producto producto = (Producto) iter.next();
         String ls_pdtDescription = producto.getDescripcion();
         String ls_pdtCode = producto.getCodigo();
         int li_pdtId = producto.getId().intValue();

         l_prod = new Product(ls_pdtDescription, 0, ls_pdtCode, true);
         l_prod.setId(li_pdtId);

         // return the new product
         return l_prod;
      }
      

      return null;
   }

   /**
    * Empties contents of bin
    */
   public void empty() throws Exception {

      // empties the recycle bin
      vProducts.clear();

      // updates database
      DispenserService dispenserService = Helper.getDispenserService();
      dispenserService.deleteRetorno(new Long(dispId));
      
   }

}